package com.product.system.imageCline.strategy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.product.system.utils.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.apache.commons.codec.binary.Base64.encodeBase64;


public class DriverLicenseOCR implements ParsePicStrategy{

    private String file;

    @Value("${alibaba.host}")
    private String host;
    @Value("${alibaba.path}")
    private String path;
    @Value("${alibaba.appcode}")
    private String appcode;

    public DriverLicenseOCR(String file){
        this.file=file;
    }

    /*
     * 获取参数的json对象
     */
    public static JSONObject getParam(int type, String dataValue) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("dataType", type);
            obj.put("dataValue", dataValue);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return obj;
    }

    @Override
    public Map<String,String> parsePicSave(String file) {
        String url = file;
        try {
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse responsee = HttpClients.createDefault().execute(httpGet);
            HttpEntity entity = responsee.getEntity();
            System.out.println(entity.toString());
            byte[] imageData = EntityUtils.toByteArray(entity);
            System.out.println(imageData+"77777777777777777777777777777");
            //将图片数据保存为临时文件
            File imgFile = File.createTempFile("tempImage", ".jpg");
            System.out.println(imgFile+"888888888888888888888888888888");
            try (FileOutputStream os = new FileOutputStream(imgFile)){
                os.write(imageData);
            }catch (Exception e){
                e.printStackTrace();
            }
            Boolean is_old_format = false;
            JSONObject configObj = new JSONObject();
            configObj.put("side","face");
            String config_str = configObj.toString();
            String method = "POST";
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Authorization","APPCODE "+appcode);

            HashMap<String, String> querys = new HashMap<>();
            String imgBase64 = "";
            try {
                byte[] content = new byte[(int) imgFile.length()];
                FileInputStream fileInputStream = new FileInputStream(imgFile);
                fileInputStream.read(content);
                fileInputStream.close();
                imgBase64 = new String(encodeBase64(content));
            }catch (IOException e){
                e.printStackTrace();
            }

            JSONObject requestObj = new JSONObject();
            try {
                if (is_old_format){
                    JSONObject obj = new JSONObject();
                    obj.put("image",getParam(50,imgBase64));
                    if (config_str.length()>0){
                        obj.put("configure",getParam(50,config_str));
                    }
                    JSONArray inputArry = new JSONArray();
                    inputArry.add(obj);
                    requestObj.put("inputs",inputArry);
                }else {
                    requestObj.put("image",imgBase64);
                    if (config_str.length()>0){
                        requestObj.put("configure",config_str);
                    }
                }
            }catch (JSONException e){
                e.printStackTrace();
            }
            String bodys = requestObj.toString();
            try {
                HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
                int stat = response.getStatusLine().getStatusCode();
                if (stat!=200){
                    System.out.println("Http code: " + stat);
                    System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
                    System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                    return null;
                }
                String res = EntityUtils.toString(response.getEntity());
                JSONObject res_obj = JSON.parseObject(res);
                if(is_old_format) {
                    JSONArray outputArray = res_obj.getJSONArray("outputs");
                    String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                    JSONObject out = JSON.parseObject(output);
                    System.out.println(out.toJSONString());
                }else{
                    System.out.println(res_obj.toJSONString());
                }

            }catch (Exception e){
                e.printStackTrace();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
